package cn.chencq.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

import javax.management.RuntimeErrorException;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

public class MD5Utils {

	public static String getMD5Code(String ming) {
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		byte[] byteArray = null;
		try {
			byteArray = ming.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		byte[] md5Bytes = md5.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}

	private static byte[] getContentBytes(String paramstr, String charset) {
		if (charset == null || "".equals(charset)) {
			return paramstr.getBytes();
		}
		try {
			byte[] arrays = paramstr.getBytes(charset);
			return arrays;
		} catch (Exception e) {
		}
		throw new RuntimeException("MD5签名过程出错");
	}

	public static String md5(String paramstr) {
		return new String(Hex.encodeHex(DigestUtils.md5(getContentBytes(paramstr, "utf-8"))));
	}
}
